package test.my_aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import test.domin.User;
import test.annotation.Whitelist;
import test.enumeration.PermTypeEnum;
import test.exception.SellerAuthorizeException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/6/24 11:35
 * @ Description:
 */
@Aspect
@Component
public class WhitelistAspect {
    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(test.annotation.Whitelist)")
    public void whitelistPointCut() {
    }

    @Before(value = "whitelistPointCut() && @annotation(whitelist)")
    public void checkAppkeyWhitelist(JoinPoint joinPoint, Whitelist whitelist) {
        // 可使用 joinPoint.getArgs() 获取Controller方法的参数
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = u.getParameterNames(method);
        Object[] args = joinPoint.getArgs();
        checkWhitelist(paramNames  , args);
        // 可以使用 whitelist 变量获取注解参数
    }


    void checkWhitelist(String[] paramNames , Object[] args) {
        //1.前端请求request，校验失败抛出异常
        //String token  = request.getHeader("Authorization");
        //2.方法参数值校验
        HttpSession session = null;
        User user = null;
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
                if ("session".equals(paramNames[i])) {
                    session = (HttpSession) args[i];
                    user = (User) session.getAttribute("user");
                    if (!PermTypeEnum.admin.getCode().equals(user.getPerm())) {
                        throw new SellerAuthorizeException();
                    }
                }
            }
        }

    }
}
